package cn.yeziji.utils;

import io.jsonwebtoken.lang.Objects;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.file.*;
import java.util.EnumSet;

/**
 * @author gzkemays
 * @date 2021/2/19 20:56
 */
public class StreamUtils {
  /**
   * inputStream Convert to outputStream
   *
   * @param in
   * @return
   * @throws IOException
   */
  public static ByteArrayOutputStream inputStreamParseOutputStream(final InputStream in)
      throws IOException {
    final ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
    int ch;
    while ((ch = in.read()) != -1) {
      swapStream.write(ch);
    }
    return swapStream;
  }
  // outputStream转inputStream
  public static ByteArrayInputStream outputStreamParseInputStream(final OutputStream out)
      throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos = (ByteArrayOutputStream) out;
    final ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
    return swapStream;
  }

  // inputStream转String
  public static String parse_String(final InputStream in) throws Exception {
    final ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
    int ch;
    while ((ch = in.read()) != -1) {
      swapStream.write(ch);
    }
    return swapStream.toString();
  }

  // OutputStream 转String
  public static String parse_String(final OutputStream out) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos = (ByteArrayOutputStream) out;
    final ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
    return swapStream.toString();
  }

  // String转inputStream
  public static ByteArrayInputStream parseInputStreamOfString(final String in) throws Exception {
    final ByteArrayInputStream input = new ByteArrayInputStream(in.getBytes());
    return input;
  }

  // String 转outputStream
  public static ByteArrayOutputStream parseOutputStreamOfString(final String in) throws Exception {
    return inputStreamParseOutputStream(parseInputStreamOfString(in));
  }
  // 合并文件
  public static void mergeFile(Path file, Path ... chunkFiles)  throws IOException {
    if ( Objects.isEmpty(chunkFiles)) {
      throw new IllegalArgumentException("分片文件不能为空");
    }
    try (FileChannel fileChannel = FileChannel.open(file, EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE))){
      for (Path chunkFile : chunkFiles) {
        try(FileChannel chunkChannel = FileChannel.open(chunkFile, EnumSet.of(StandardOpenOption.READ))){
          chunkChannel.transferTo(0, chunkChannel.size(), fileChannel);
        }
      }
    }
  }


  /**
   * 对文件按照指定大小进行分片，在文件所在目录生成分片后的文件块儿
   * @param file
   * @param chunkSize
   * @throws IOException
   */
  public static void chunkFile(Path file, long chunkSize) throws IOException {
    if (Files.notExists(file) || Files.isDirectory(file)) {
      throw new IllegalArgumentException("文件不存在:" + file);
    }
    if (chunkSize < 1) {
      throw new IllegalArgumentException("分片大小不能小于1个字节:" + chunkSize);
    }
    // 原始文件大小
    final long fileSize = Files.size(file);
    // 分片数量
    final long numberOfChunk = fileSize % chunkSize == 0 ? fileSize / chunkSize : (fileSize / chunkSize) + 1;
    // 原始文件名称
    final String fileName = file.getFileName().toString();
    // 读取原始文件
    try(FileChannel fileChannel = FileChannel.open(file, EnumSet.of(StandardOpenOption.READ))){
      for (int i = 0; i < numberOfChunk; i++) {
        long start = i * chunkSize;
        long end = start + chunkSize;
        if (end > fileSize) {
          end = fileSize;
        }
        // 分片文件名称
        Path chunkFile = Paths.get(fileName + "-" + (i + 1));
        try (FileChannel chunkFileChannel = FileChannel.open(file.resolveSibling(chunkFile),
                EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE))){
          // 返回写入的数据长度
          fileChannel.transferTo(start, end - start, chunkFileChannel);
        }
      }
    }
  }
}
